<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工单编码" prop="workorderCode">
        <el-input v-model="queryParams.workorderCode" placeholder="请输入工单编码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="工单名称" prop="workorderName">
        <el-input v-model="queryParams.workorderName" placeholder="请输入工单名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="工单类型" style="width: 200px;" prop="orderType">
        <el-select v-model="queryParams.orderType" placeholder="请选择工单类型" clearable>
          <el-option v-for="dict in sys_workorder_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="工单来源" prop="orderSource">
        <el-input v-model="queryParams.orderSource" placeholder="请输入工单来源" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="产品编号" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入产品编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="客户名称" prop="clientName">
        <el-input v-model="queryParams.clientName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="需求日期" prop="requestDate">
        <el-date-picker clearable v-model="queryParams.requestDate" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择需求日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="workorderList">
      <el-table-column label="工单编码" align="center" prop="workorderCode" />
      <el-table-column label="工单名称" align="center" prop="workorderName" />
      <el-table-column label="工单类型" align="center" prop="orderType">
        <template #default="scope">
          <dict-tag :options="sys_workorder_type" :value="scope.row.orderType" />
        </template>
      </el-table-column>
      <el-table-column label="工单来源" align="center" prop="orderSource" />
      <el-table-column label="产品编号" align="center" prop="productCode" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="规格型号" align="center" prop="productSpc" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="工单数量" align="center" prop="quantity" width="80" />
      <el-table-column label="已生产数量" align="center" prop="quantityProduced" width="120" />
      <el-table-column label="调整数量" align="center" prop="quantityChanged" width="80" />
      <el-table-column label="需求日期" align="center" prop="requestDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.requestDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status" width="80" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="130">
        <template #default="scope">
          <el-button link type="primary" icon="EditPen" @click="handleUpdate(scope.row)"
            v-hasPermi="['workorder:workorder:finished']" v-if="scope.row.status == '已确认'">排产</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 生产排产对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body :z-index="1000">
      <el-form ref="workorderRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工单编码" prop="workorderCode">
              <div style="display: flex; align-items: center;">
                <el-input v-model="form.workorderCode" placeholder="请输入工单编码" disabled />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单名称" prop="workorderName">
              <el-input v-model="form.workorderName" placeholder="请输入工单名称" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工单类型" prop="orderType">
              <el-select v-model="form.orderType" placeholder="请选择工单类型" style="width: 100%" disabled>
                <el-option v-for="dict in sys_workorder_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单来源" prop="orderSource">
              <el-radio-group v-model="form.orderSource" disabled>
                <el-radio value="客户订单">客户订单</el-radio>
                <el-radio value="库存备货">库存备货</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单编号" prop="orderId">
              <el-input v-model="form.orderId" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求日期" prop="requestDate">
              <el-date-picker clearable v-model="form.requestDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择需求日期" style="width: 100%" disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="产品编号" prop="productCode">
          <div style="display: flex;">
            <el-input v-model="form.productCode" placeholder="请输入产品编号" style="flex: 1;" disabled />
          </div>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="productSpc">
              <el-input v-model="form.productSpc" placeholder="请输入规格型号" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单位" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" placeholder="请输入单位" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单数量" prop="quantity">
              <el-input v-model="form.quantity" placeholder="请输入数量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户编码" prop="clientCode">
              <el-input v-model="form.clientCode" placeholder="请输入客户编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="clientName">
              <el-input v-model="form.clientName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 生产流程 -->
      <el-card>
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick"> 
          <el-tabs v-model="activeTab" @tab-click="handleTabChange">
            <el-tab-pane label="生产加工" name="processing"></el-tab-pane>
            <el-tab-pane label="QCC质检" name="quality"></el-tab-pane>
            <el-tab-pane label="包装" name="packaging"></el-tab-pane>
          </el-tabs>

          <!-- 根据 activeTab 渲染不同数据 -->
        <div class="content-area">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button
                    type="primary"
                    plain
                    icon="Plus"
                    @click="handleAdd"
                    v-hasPermi="['task:task:add']"
                  >新增</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    type="success"
                    plain
                    icon="Edit"
                    :disabled="singleTask"
                    @click="handleUpdateTask"
                    v-hasPermi="['task:task:edit']"
                  >修改</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    type="danger"
                    plain
                    icon="Delete"
                    :disabled="multipleTask"
                    @click="handleDeleteTask"
                    v-hasPermi="['task:task:remove']"
                  >删除</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    type="warning"
                    plain
                    icon="Download"
                    @click="handleExportTask"
                    v-hasPermi="['task:task:export']"
                  >导出</el-button>
                </el-col>
                <right-toolbar v-model:showSearch="showSearchTask" @queryTable="getListTask(workorderId)"></right-toolbar>
              </el-row>
              <el-table v-loading="loadingTask" :data="taskList" @selection-change="handleSelectionChangeTask">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="任务编号" align="center" prop="taskCode" />
                <el-table-column label="任务名称" align="center" prop="taskName" />
                <el-table-column label="工作站编号" align="center" prop="workstationCode" />
                <el-table-column label="工作站名称" align="center" prop="workstationName" />
                <el-table-column label="排产数量" align="center" prop="quantity" />
                <el-table-column label="已生产数量" align="center" prop="quantityProduced" />
                <el-table-column label="开始生产时间" align="center" prop="startTime" width="180">
                  <template #default="{row}">
                    <span>{{ row.startTime ? formatTime(row.startTime) : '请选择开始时间' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="生产时长" align="center" prop="duration" />
                <el-table-column label="完成生产时间" align="center" prop="endTime" width="180">
                  <template #default="{row}">
                    <span>{{ row.endTime ? formatTime(row.endTime) : '请选择结束时间' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
                  <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdateTask(scope.row)" v-hasPermi="['task:task:edit']">修改</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDeleteTask(scope.row)" v-hasPermi="['task:task:remove']">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                v-show="totaltotalTask>0"
                :total="totaltotalTask"
                v-model:page="queryParamsTask.pageNum"
                v-model:limit="queryParamsTask.pageSize"
                @pagination="getListTask(workorderId)"
              />
              <!-- 添加或修改生产任务对话框 -->
              <el-dialog  v-model="openTask" :z-index="2000" :title="titleTask" width="900px"   @close="closeTDialog">
                <el-row :gutter="15">
                  <el-form ref="taskRef" :model="formtask" :rules="rulesTask" size="default" label-width="100px">
                    <el-row gutter="15">
                        <el-col :span="10">
                          <el-form-item label="任务编号" prop="taskCode" >
                            <el-input v-model="formtask.taskCode" type="text" placeholder="请输入任务编号"
                              :style="{width: '100%'}" disabled></el-input>
                          </el-form-item>
                        </el-col>
                          <!-- 自动生成文字移到开关后面 -->
                        <el-switch   v-model="autoGenerateCodeWork"  style="margin-left: 10px;"  @change="handleCodeSwitchChangeWork"  ></el-switch>
                        <span style="margin-left: 5px;">自动生成</span>
                        <el-col :span="11">
                          <el-form-item label="任务名称" prop="taskName">
                            <el-input v-model="formtask.taskName" type="text" placeholder="请输入任务名称" clearable
                              :style="{width: '100%'}"></el-input>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    <el-col :span="15">
                      <el-form-item label="工作站" prop="workstationName">
                        <el-input v-model="formtask.workstationName" type="text" placeholder="请输入工作站" clearable
                          :style="{width: '100%'}" disabled></el-input>
                        <el-icon @click="showTask" style="border: 1px solid #DCDFE6;width: 30px;height: 30px;background-color: #F5F7FA;cursor: pointer;position: relative;left:410px;top: -31px;"><Search /></el-icon>
                      </el-form-item>
                    </el-col>
                    <el-col :span="17">
                      <el-form-item label="排产数量" prop="quantity">
                        <el-input-number v-model="formtask.quantity" placeholder="排产数量"></el-input-number>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-row gutter="15">
                        <el-col :span="8">
                          <el-form-item label="开始时间" prop="startTime">
                              <el-date-picker
                                  v-model="formtask.startTime"
                                  type="datetime"
                                  placeholder="请选择开始时间"
                                  :size="size" clearable
                                  :style="{width: '100%'}"
                                  value-format="YYYY-MM-DD HH:mm:ss"
                                />
                          </el-form-item>
                        </el-col>
                       
                        <el-col :span="8">
                          <el-form-item label="生产时长" prop="duration">
                            <el-input-number v-model="formtask.duration" placeholder="生产时长"></el-input-number>
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item label="完成时间" prop="endTime">
                            <el-date-picker
                                v-model="formtask.endTime"
                                type="datetime"  
                                placeholder="自动计算"
                                :size="size"
                                :style="{width: '100%'}"
                                value-format="YYYY-MM-DD HH:mm:ss"  
                                :disabled="true"  
                              />
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </el-col>
                  </el-form>
                </el-row>
                <template #footer>
                  <div class="dialog-footer">
                    <el-button type="primary" @click="submitFormTask">确 定</el-button>
                    <el-button @click="cancelTask">取 消</el-button>
                  </div>
                </template>
              </el-dialog>

              <!-- 查看工作站 -->
              <el-dialog v-model="openWork" width="1100px" @close="closeWorkDialog" :z-index="3000">
                  <el-form :model="queryParamsWork" ref="queryRef" :inline="true" v-show="showSearchWork" label-width="100px">
                  <el-form-item label="工作站编码" prop="workstationCode">
                    <el-input v-model="queryParamsWork.workstationCode" placeholder="请输入工作站编码" clearable @keyup.enter="handleQueryWork" />
                  </el-form-item>
                  <el-form-item label="所在车间名称" prop="workshopName">
                    <el-select v-model="queryParamsWork.workshopCode" placeholder="请选择车间" clearable style="width: 240px">
                      <el-option v-for="item in workshopOptions" :key="item.workshopId" :label="item.workshopName"
                        :value="item.workshopCode" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="所属工序" prop="processName">
                    <el-select v-model="queryParamsWork.processCode" placeholder="请选择工序" clearable style="width: 240px">
                      <el-option v-for="(item, index) in processCodeOptions" :key="item.processId" :label="item.processName"
                        :value="item.processCode" :disabled="item.disabled"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQueryWork">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQueryWork">重置</el-button>
                  </el-form-item>
                </el-form>
                <el-table v-loading="loadingWork" ref="workRef" :data="workstationList" @selection-change="handleSelectionChangeWork">
                  <el-table-column type="selection" width="55" align="center" />
                  <el-table-column label="工作站编码" align="center" prop="workstationCode" />
                  <el-table-column label="工作站名称" align="center" prop="workstationName" />
                  <el-table-column label="工作站地点" align="center" prop="workstationAddress" />
                  <el-table-column label="所在车间名称" align="center" prop="workshopName" />
                  <el-table-column label="工序名称" align="center" prop="processName" />
                  <el-table-column label="备注" align="center" prop="remark" />
                </el-table>
                <pagination v-show="totalWork > 0" :total="totalWork" v-model:page="queryParamsWork.pageNum"
                  v-model:limit="queryParamsWork.pageSize" @pagination="getListWork" />

                  <div style="position: relative;left:-500px;">
                  <el-button style="margin-left: 950px;" type="primary" @click="confirmSelectedItemWork">确 认</el-button>
                  <el-button @click="cancelWork">关 闭</el-button>
                  </div>
              </el-dialog>   
        </div>
        </el-tabs>
      </el-card>
          <div style="position: relative;left:-500px;top:20px">
            <el-button style="margin-left: 950px;" type="primary" @click="confirmSelectedItemp">确 认</el-button>
            <el-button style="margin-left: 1050px;margin-top:-50px" @click="cancelP">关 闭</el-button>
          </div>
    </el-dialog>
  </div>
</template>

<script setup name="Workorder">

//默认激活标签页
const activeTab = ref('processing');
import { listWorkorder, getWorkorder} from "@/api/schedule/schedule"
// import { ref } from 'vue'
const { proxy } = getCurrentInstance()
const { sys_workorder_type } = proxy.useDict('sys_workorder_type')
const workorderList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const total = ref(0)
const title = ref("")
// const activeTab=ref()
const processingData =ref([])
const qualityData =ref([])
const packagingData =ref([])
//根据当前标签，返回对应的数据源
const taskList = computed(() => {
  switch (activeTab.value) {
    case 'processing':
      return processingData.value;
    case 'quality':
      return qualityData.value;
    case 'packaging':
      return packagingData.value;
    default:
      return [];
  }
});
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workorderCode: null,
    workorderName: null,
    orderType: null,
    quantity: null,
    orderSource: null,
    productCode: null,
    productName: null,
    productId: null,
    clientCode: null,
    clientName: null,
    requestDate: null,

  },

})
const { queryParams, form, rules } = toRefs(data)
/** 查询生产工单列表 */
function getList() {
  loading.value = true
  listWorkorder(queryParams.value).then(response => {
    //console.log(response.rows);
    response.rows.forEach(row => {
      row.orderSource = row.orderSource == 1 ? '客户订单' : '库存备货'
    })
    workorderList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
// 表单重置
function reset() {
  form.value = {
    workorderId: null,
    workorderCode: null,
    workorderName: null,
    orderType: null,
    orderSource: null,
    sourceCode: null,
    orderId: null,
    productId: null,
    productCode: null,
    productName: null,
    productSpc: null,
    unitOfMeasure: null,
    quantity: null,
    quantityProduced: null,
    quantityChanged: null,
    quantityScheduled: null,
    clientId: null,
    clientCode: null,
    clientName: null,
    batchCode: null,
    requestDate: null,
    parentId: null,
    ancestors: null,
    finishDate: null,
    status: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("workorderRef")
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}
const productCode=ref()//当前产品id
const workorderId=ref()//生产工单id
const workorderCode=ref()
const workorderName=ref()

const processList=ref([]) //存储工艺过程集合
import {getRouteId,addgetTask,updataWorkerTask} from '@/api/workorder/workorder'
/** 排产按钮操作 */
async function handleUpdate(row) {
  console.log("row")
  console.log(row)
  productCode.value=row.productCode
  workorderId.value=row.workorderId
  workorderCode.value=row.workorderCode
  workorderName.value=row.workorderName
  if(row.task=='N'){
    await getRouteId(row.productCode).then(res=>{
    // console.log(res);
    res.data.forEach(item => {
      const filteredItem = {
        // taskId: item.processId,
        taskCode: item.processCode,
        taskName: item.processName,
        workorderId:workorderId.value,
        workorderCode:workorderCode.value,
        workorderName:workorderName.value
      };
      processList.value.push(filteredItem);
    });
    })
  //增加任务
    await addgetTask(processList.value).then(res=>{
      // console.log("result");
      // console.log(res); 
    })
  }
  //修改工单的是否已添加排产任务
  updataWorkerTask(row.workorderCode)
  getList()//重新加载工单
  getListTask(row.workorderId)
  reset()
  autoGenerateCodeWork.value=false;//隐藏自动生成工单编号按钮
  const _workorderId = row.workorderId || ids.value
  getWorkorder(_workorderId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "生产排产"
  })

}
getList()

//生产加工
import { listTask, getTask, delTask, addTask, updateTask } from "@/api/task/task"
import { ref, reactive, toRefs, getCurrentInstance, watch } from 'vue';
import { formatTime } from '@/utils/format';

// const taskList = ref([])
const openTask = ref(false)
const openWork = ref(false)
const loadingTask = ref(true)
const showSearchTask = ref(true)
const idsTask = ref([])
const singleTask = ref(true)
const multipleTask = ref(true)
const titleTask = ref("")

const dataTask = reactive({
  formtask: {},
  queryParamsTask: {
    pageNum: 1,
    pageSize: 10,
  },
 rulesTask: {
   taskCode: [{
      required: true,
      message: '请输任务编号',
      trigger: 'blur'
    }],
     taskName: [{
      required: true,
      message: '请输入任务名称',
      trigger: 'blur'
    }],
    workstationName: [{
      required: true,
      message: '请输入工作站',
      trigger: 'blur'
    }],
    quantity: [{
      required: true,
      message: '排产数量',
      trigger: 'blur'
    }],
    startTime: [{
      required: true,
      message: '请选择开始时间',
      trigger: 'change'
    }],
    duration: [{
      required: true,
      message: '生产时长',
      trigger: 'blur'
    }],
    endTime: [],
  }
})

const { queryParamsTask, formtask, rulesTask } = toRefs(dataTask)

/** 根据生产工单id查询生产任务列表 */
async function getListTask(workorderId) {
  loadingTask.value = true
   try {
    // 清空
      processingData.value = [];
      qualityData.value = [];
      packagingData.value = [];
    const response = await listTask(workorderId); 
    console.log("response");
    console.log(response);
    
    response.data.forEach(item => {
      
      const prefix = item.taskCode.split("-")[0]
      if(prefix === 'PROC'){
        processingData.value.push(item);
      } else if(prefix === 'QC'){
        qualityData.value.push(item);
      } else if(prefix === 'PK'){
        packagingData.value.push(item);
      }
    });
  } catch (error) {
    console.error("加载行列表失败：", error);
    proxy.$modal.msgError("加载行数据失败，请重试");
  } finally {
    // 无论成功/失败，都关闭加载状态
    loadingTask.value = false
  }
}
//切换标签时，重新获取数据
function handleTabChange(tab) {
  activeTab.value = tab.name;
  getListTask(workorderId.value);
}
// 取消按钮
function cancelTask() {
  openTask.value = false
  autoGenerateCodeWork.value=false
  resetTask()
}
//点击❌关闭新增或者修改生产任务
function closeTDialog(){
  openTask.value = false
  autoGenerateCodeWork.value=false
  resetTask()
}
// 表单重置
function resetTask() {
  formtask.value = {
    taskId: null,
    taskCode: null,
    taskName: null,
    workorderId: null,
    workorderCode: null,
    workorderName: null,
    workstationId: null,
    workstationCode: null,
    workstationName: null,
    routeId: null,
    routeCode: null,
    processId: null,
    processCode: null,
    processName: null,
    itemId: null,
    itemCode: null,
    itemName: null,
    specification: null,
    unitOfMeasure: null,
    quantity: null,
    quantityProduced: null,
    quantityQuanlify: null,
    quantityUnquanlify: null,
    quantityChanged: null,
    clientId: null,
    clientCode: null,
    clientName: null,
    clientNick: null,
    startTime: null,
    duration: null,
    endTime: null,
    colorCode: null,
    requestDate: null,
    status: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("taskRef")
}

// 生产任务多选框选中数据
function handleSelectionChangeTask(selection) {
  idsTask.value = selection.map(item => item.taskId)
  singleTask.value = selection.length != 1
  multipleTask.value = !selection.length
}

/** 新增生产任务按钮操作 */
function handleAdd() {
  if (activeTab.value === 'processing') {
    console.log('生产加工-新增');
  } else if (activeTab.value === 'quality') {
    console.log('QCC质检-新增');
  } else if (activeTab.value === 'packaging') {
    console.log('包装-新增');
  }
  resetTask()
  openTask.value = true
  titleTask.value = "添加生产任务"
}

/** 修改生产任务按钮操作 */
function handleUpdateTask(row) {
  resetTask()
  const _taskId = row.taskId || idsTask.value
  getTask(_taskId).then(response => {
    formtask.value = response.data

    openTask.value = true
    titleTask.value = "修改生产任务"
  })
}

const resultTime = ref('');
// 3. 监听 startTime 和 duration 的变化，实时计算结束时间
watch(
  // 监听的目标：开始时间和生产时长
  [() => formtask.value.startTime, () => formtask.value.duration],
  // 变化后的回调函数
  ([newStartTime, newDuration]) => {
    // 只有当开始时间和时长都有效时，才计算结束时间
    if (newStartTime && newDuration && newDuration > 0) {
      try {
        // 解析开始时间（兼容浏览器差异）
        const dateParts = newStartTime.split(' ')[0].split('-');
        const timeParts = newStartTime.split(' ')[1].split(':');
        const date = new Date(
          parseInt(dateParts[0]),
          parseInt(dateParts[1]) - 1,  // 月份从 0 开始
          parseInt(dateParts[2]),
          parseInt(timeParts[0]),
          parseInt(timeParts[1]),
          parseInt(timeParts[2])
        );

        // 检查日期有效性
        if (isNaN(date.getTime())) throw new Error("开始时间格式错误");

        // 计算结束时间（时长转毫秒：小时 * 3600000）
        const durationMs = newDuration * 3600000;
        const newTime = new Date(date.getTime() + durationMs);

        // 格式化结束时间（与开始时间格式一致）
        const year = newTime.getFullYear();
        const month = String(newTime.getMonth() + 1).padStart(2, '0');
        const day = String(newTime.getDate()).padStart(2, '0');
        const hours = String(newTime.getHours()).padStart(2, '0');
        const minutes = String(newTime.getMinutes()).padStart(2, '0');
        const seconds = String(newTime.getSeconds()).padStart(2, '0');

        // 更新结果时间，并同步到表单的 endTime（表单控件会自动渲染）
        resultTime.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        formtask.value.endTime = resultTime.value;
      } catch (error) {
        console.error("计算结束时间失败：", error);
        formtask.value.endTime = '';  // 计算失败时清空
      }
    } else {
      // 开始时间或时长无效时，清空结束时间
      formtask.value.endTime = '';
      resultTime.value = '';
    }
  },
  // 配置项：初始时立即执行一次（可选，确保页面加载时已有值也能计算）
  { immediate: true }
);

/** 提交生产任务按钮 */
function submitFormTask() {
  formtask.value.workorderId= workorderId.value
  formtask.value.workorderCode= workorderCode.value
  formtask.value.workorderName= workorderName.value
    proxy.$refs["taskRef"].validate(valid => {
      if (valid) {
        if (formtask.value.taskId != null) {
          updateTask(formtask.value).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            openTask.value = false
            getListTask(formtask.value.workorderId)
          })
        } else {
          addTask(formtask.value).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            openTask.value = false
            getListTask(formtask.value.workorderId)
          })
        }
      }
      autoGenerateCodeWork.value=false//自动生成关闭
  })
}

/** 删除按钮操作 */
function handleDeleteTask(row) {
  
  const _taskIds = row.taskId || idsTask.value
  proxy.$modal.confirm('是否确认删除生产任务编号为"' + _taskIds + '"的数据项？').then(function() {
    return delTask(_taskIds)
  }).then(() => {
    getListTask(workorderId.value)
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExportTask() {
  proxy.download('task/task/export', {
    ...queryParamsTask.value
  }, `task_${new Date().getTime()}.xlsx`)
}
// 自动生成编码开关状态
const autoGenerateCodeWork = ref(false)
// 自动生成任务编号
function handleCodeSwitchChangeWork() {
  if (autoGenerateCodeWork.value) {
    generateWorkshopCodeWork()
  } else {
    formtask.value.taskCode = null  // 关闭时清空手动输入   
  }
}
/** 生成仓库编码（规则：WS-YYYYMMDDHHmmss，如WS-20240520143025） */
function generateWorkshopCodeWork() {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  const second = String(date.getSeconds()).padStart(2, '0')
  let prefix = '';
  if (activeTab.value === 'processing') prefix = 'PROC';   // 生产加工前缀
  if (activeTab.value === 'quality') prefix = 'QC';     // QCC质检前缀
  if (activeTab.value === 'packaging') prefix = 'PK';   // 包装前缀
  
  const code = `${prefix}-${year}${month}${day}${hour}${minute}${second}`;
  formtask.value.taskCode = code
}
// 查看工作站
 function showTask() {
    openWork.value=true
}
// 确认关闭生产排产
function confirmSelectedItemp(){
  open.value=false
}
function cancelP(){
   open.value=false
}
// 工作站
import { listWorkstation,listWorkshop, listProcess } from "@/api/workstation/workstation"
const workstationList = ref([])
const loadingWork = ref(true)
const showSearchWork = ref(true)
const idsWork = ref([])
const singleWork = ref(true)
const multipleWork = ref(true)
const totalWork = ref(0)
const workshopOptions = ref([])//车间下拉列表
const processCodeOptions = ref([])//工序下拉列表
const dataWork = reactive({
  formWork: {},
  queryParamsWork: {
    pageNum: 1,
    pageSize: 10,
    workstationCode: null,
    workstationName: null,
    workshopCode: null,
    workshopName: null,//所属车间
    processCode: null,
    processName: null,//所属工序
  },

})
const { queryParamsWork } = toRefs(dataWork)
/** 查询工作站列表 */
function getListWork() {
  loadingWork.value = true
  listWorkstation(queryParamsWork.value).then(response => {
    workstationList.value = response.rows
    totalWork.value = response.total
    loadingWork.value = false
  })
}
//查询车间列表
function getWorkshopList() {
  loadingWork.value = true
  listWorkshop().then(response => {
    workshopOptions.value = response.data
    loadingWork.value = false

  })
}
//查询工序列表
function getProcessList() {
  loadingWork.value = true
  listProcess().then(response => {
    //console.log("工序", response);
    processCodeOptions.value = response.data
    loadingWork.value = false
  })
}
/** 搜索按钮操作 */
function handleQueryWork() {
  queryParamsWork.value.pageNum = 1
  getListWork()
}
/** 重置按钮操作 */
function resetQueryWork() {
  proxy.resetForm("queryRef")
  handleQueryWork()
}
getListWork()
getWorkshopList()
getProcessList()
const selectedItemWork = ref('')//用于选中的数据
// 多选框选中数据
function handleSelectionChangeWork(selection) {
  idsWork.value = selection.map(item => item.workstationId)
  singleWork.value = selection.length != 1
  multipleWork.value = !selection.length
  selectedItemWork.value = selection.length > 0 ? selection[0] : null;
}

const workRef = ref(null); //获取el-table的实例
// 选中按钮
function confirmSelectedItemWork() {
  if (!selectedItemWork.value) {
    proxy.$modal.msgWarning("请选择一个工作站");
    return;
  }
  //console.log(selectedItemWork.value);
  // 将选中的工作站信息回填到表单
  formtask.value.workshopName = selectedItemWork.value.workshopName;
  formtask.value.processName = selectedItemWork.value.processName;
  formtask.value.workshopCode = selectedItemWork.value.workshopCode;
  formtask.value.workstationAddress = selectedItemWork.value.workstationAddress;
  formtask.value.workstationCode = selectedItemWork.value.workstationCode;
  formtask.value.workstationId = selectedItemWork.value.workstationId;
  formtask.value.workstationName = selectedItemWork.value.workstationName;
  // 关闭工作站选择框，返回工单表单
  openWork.value = false;
  //清空选项
  if (workRef.value) {
    workRef.value.clearSelection(); // 清空表格多选框选中状态
  }
}
//关闭工作站
function cancelWork(){
  openWork.value = false;
  if (workRef.value) {
    workRef.value.clearSelection(); // 清空表格多选框选中状态
  }
}
//点击❌关闭工作站
function closeWorkDialog(){
  openWork.value = false;
  if (workRef.value) {
    workRef.value.clearSelection(); // 清空表格多选框选中状态
  }
}
</script>
